package com.jbit.auth;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenUtil {
    private final static String CLAIM_KEY_USERNAME = "sub";
    private final static String CLAIM_KEY_CREATED = "created";

    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;

    /**
     * 根据用户信息生成token
     *
     * @param username
     * @return
     */
    public String generatorToken(String username) {
        Map<String, Object> claims = new HashMap<>();

        claims.put(CLAIM_KEY_USERNAME, username);
        claims.put(CLAIM_KEY_CREATED, new Date());

        return generatorToken(claims);
    }

    /**
     * 根据荷载生成JWT Token
     *
     * @param claims
     * @return
     */
    private String generatorToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims) //荷载
                .setExpiration(generatorExpirationDate())//失效时间
                .signWith(SignatureAlgorithm.HS512, secret)//签名
                .compact();//生成
    }

    /**
     * 生成token 失效时间
     *
     * @return
     */
    private Date generatorExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     * 根据token获取用户名
     *
     * @param token
     * @return
     */
    public String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 根据token获取荷载
     *
     * @param token
     * @return
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)//签名
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return claims;
    }

    /**
     * 验证token是否有效
     * 1 token是否失效
     * 2 token荷载里的用户名是否和UserDetails里的用户名是否一致
     *
     * @param token
     * @param username
     * @return
     */
    public boolean validateToken(String token, String username) {
        String name = getUserNameFromToken(token);
        return name.equals(username) && !isTokenExpiration(token);
    }

    /**
     * 是否能被刷新
     *
     * @param token
     * @return
     */
    public boolean canRefresh(String token) {
        return !isTokenExpiration(token);
    }

    /**
     * 刷新token
     *
     * @param token
     * @return
     */
    public String refreshToken(String token) {
        Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generatorToken(claims);
    }

    /**
     * 判断token是否失效
     *
     * @param token
     * @return true: 失效   false：没失效
     */
    private boolean isTokenExpiration(String token) {
        //获取荷载
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration().before(new Date());
    }
}
